<?php

CRequire('AuthKernel', 'AuthRecord');

define ('kAuthUserName', 'kAuthUserName');
define ('kAuthUserPassword', 'kAuthUserPassword');
define ('kAuthUserPrivileges', 'kAuthUserPrivileges');

class AuthUserKernel extends AuthKernel {
	var $_Storage;
	function Init(&$storage) {
		$a = func_num_args();
		if ($a > 0)
			$this->SetStorage($storage);		
	}
	
	function SetStorage(&$storage) {
		$this->_Storage = &$storage;
	}
	
	function &Authenticate($credentials, $entity = null) {
		if (is_null($entity))
			$entity = 'AuthUser';
			
		$conds = array(kDKEntity => $entity);
		if (isset($credentials[kAuthUserName]))
			$conds['username'] = $credentials[kAuthUserName];
		if (isset($credentials[kAuthUserPassword]))
			$conds['password_hash'] = sha1($credentials[kAuthUserPassword]);
		
		if (sizeof($conds) == 0) {
			// TODO errore?
			$x = CError::NotFound(null);
			return $x;
		}
	
		// TODO classe <-> entità
		$x = &$this->_Storage->FindMatching($conds);
		if (CErr($x))
			return $x;
		
		if (is_array($privs = @$credentials[kAuthUserPrivileges])) {
			foreach($privs as $priv) {
				if (!in_array($priv, $x->Privileges)) {
					$x = CError::NotFound(null);
					return $x;
				}
			}
		}
		
		return $x;
	}
}

class AuthUser extends AuthRecord {
}
DKRecord::SetSchemaForClass('AuthUser',
	array(
		'Name' => kCStringType,
		'PasswordHash' => kCStringType,
		'Privileges' => CType::ArrayOf(kCStringType),
		
		kDKIdentifiers => array('Name')
	)
);

?>